package com.xh3140.android.widget.dialog.view;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.LinearLayoutCompat;

import com.xh3140.android.widget.dialog.BaseDialog;
import com.xh3140.android.widget.dialog.params.FooterParams;


/**
 * 对话框底部视图
 */
public final class FooterView extends LinearLayoutCompat {

    public FooterView(@NonNull Context context) {
        super(context);
        setOrientation(HORIZONTAL);
        setShowDividers(SHOW_DIVIDER_MIDDLE);
        setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    }

    public <D extends BaseDialog<?>> FooterView(@NonNull Context context, @NonNull D dialog, @NonNull FooterParams<D> params) {
        this(context);
        configView(dialog, params);
    }

    /**
     * 配置视图
     *
     * @param dialog 对话框
     * @param params 底部视图配置属性
     */
    public <D extends BaseDialog<?>> void configView(@NonNull D dialog, @NonNull FooterParams<D> params) {
        if (getChildCount() > 0) {
            removeAllViews();
        }
        for (int i = 0; i < params.buttons.size(); ++i) {
            final int index = i;
            final ButtonView buttonView = new ButtonView(getContext(), params.buttons.get(i));
            buttonView.setOnClickListener(v -> {
                if (params.listener != null) {
                    params.listener.onClickButton(dialog, index, buttonView);
                } else {
                    dialog.dismiss();
                }
            });
            addView(buttonView);
        }
        if (getChildCount() == 0) {
            setVisibility(GONE);
        }
    }
}